import os
import time
import os.path
import script_logs

root_path = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'cdb')
log_path = os.path.join(root_path, 'log')

class clean:

    def __init__(self, file_url, file_date):
        """
        用于删除文件
        :param file_url:
        file_url表示需要清理文件的目录
        file_date表示日志文件保存的时长
        """
        self.file_url = file_url
        self.file_date = file_date

    def DelFile(self):
        file = list(os.listdir(self.file_url))
        msg = "开始清理文件"
        logs = script_logs.logs(msg=msg, log_path=log_path, level='info')
        logs.ScriptLogs()
        for f in range(len(file)):
            filedate = os.path.getmtime(self.file_url + file[f])
            nowdate = time.time()
            num = (nowdate - filedate) / 60 / 60 / 24
            if num > float(self.file_date):
            # if num > 30:
                try:
                    os.remove(self.file_url + file[f])
                    msg = "删除文件- %s" %(self.file_url + file[f])
                    logs = script_logs.logs(msg=msg, log_path=log_path, level='info')
                    logs.ScriptLogs()
                except Exception as err:
                    logs = script_logs.logs(msg=err, log_path=log_path, level='error')
                    logs.ScriptLogs()
        msg = "清理文件结束"
        logs = script_logs.logs(msg=msg, log_path=log_path, level='info')
        logs.ScriptLogs()